package top.zpengblog.db2document.ui.listenner;

import top.zpengblog.db2document.constant.SysConstant;
import top.zpengblog.db2document.engine.EngineConfig;
import top.zpengblog.db2document.engine.EngineFileType;
import top.zpengblog.db2document.engine.EngineTemplateType;
import top.zpengblog.db2document.engine.freemark.FreemarkerTemplateEngine;
import top.zpengblog.db2document.jdbc.AbstractMetadataCollector;
import top.zpengblog.db2document.jdbc.MysqlMetadataCollector;
import top.zpengblog.db2document.model.ConnectionInfo;
import top.zpengblog.db2document.model.DataModel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author ZhiPeng.Lin (codingjava@qq.com)
 * @version 1.0.0
 * @date 2022/1/27 23:48
 */
public class ChooseTableListener implements ActionListener {

    private ConnectionInfo connectionInfo;

    public ChooseTableListener(JTextField address, JTextField port, JTextField database,
                                  JTextField userName, JTextField userPassword) {
        this.connectionInfo = new ConnectionInfo(address, port, database, userName, userPassword);
    }

    public ChooseTableListener() {
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        AbstractMetadataCollector collector = new MysqlMetadataCollector();
        DataModel dataModel = null;
        try {
            dataModel = collector.collectMetadata(connectionInfo);
        } catch (Exception exception) {
            JOptionPane.showMessageDialog(null, "获取元数据异常！msg = " + exception.getMessage(), "结果", JOptionPane.ERROR_MESSAGE);
        }
        if (null != dataModel) {
            exportFile(dataModel);
        } else {
            JOptionPane.showMessageDialog(null, "获取元数据为空，不生成文档！", "结果", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void exportFile(DataModel dataModel) {
        //生成配置
        EngineConfig engineConfig = EngineConfig.builder()
                //生成文件路径
                .fileOutputDir(System.getProperty("user.dir"))
                //打开目录
                .openOutputDir(true)
                //文件类型
                .fileType(EngineFileType.WORD)
                //生成模板实现
                .produceType(EngineTemplateType.freemarker).build();
        FreemarkerTemplateEngine templateEngine = new FreemarkerTemplateEngine(engineConfig);
        try {
            templateEngine.produce(dataModel, SysConstant.DEFAULT_FILE_NAME + "V" + SysConstant.VERSION_NUMBERS.get());
        } catch (Exception exception) {
            JOptionPane.showMessageDialog(null, "生成文档失败！msg = " + exception.getMessage(), "结果", JOptionPane.ERROR_MESSAGE);
        }
        SysConstant.VERSION_NUMBERS.incrementAndGet();
    }
}
